/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.dusty.fs.filesystem.data;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import ru.dusty.fs.filesystem.utils.PrimitiveSizes;

/**
 *
 * @author Dusty
 */
public class Block {
    
    private RandomAccessFile raf;
    
    private File file;
    
    public Block(File file, String mode) throws FileNotFoundException {
        this.file = file;
        raf = new RandomAccessFile(file, mode);
    }
    
    public Block(File file) throws FileNotFoundException {
        this(file, "rw");
    }
    
    public void readMetaData(MetaData data) throws IOException {
        raf.seek(0);
        data.read(raf);
    }
    
    public void writeMetaData(MetaData data) throws IOException {
        raf.seek(0);
        data.write(raf);
    }
    
    public int getNextBlock() throws IOException {
        int result = 0;
        long oldPos = raf.getFilePointer();
        raf.seek(raf.length() - PrimitiveSizes.sizeof(result));
        result = raf.readInt();
        raf.seek(oldPos);
        
        return result;
    }
    
    public void setNextBlock(int val) throws IOException {
        long oldPos = raf.getFilePointer();
        raf.seek(raf.length() - PrimitiveSizes.sizeof(val));
        raf.writeInt(val);
        raf.seek(oldPos);
    }
    
    public void seek(long pos) throws IOException {
        raf.seek(pos);
    }
    
    public long pos() throws IOException {
        return raf.getFilePointer();
    }
    
    public int read() throws IOException {
        return raf.readInt();
    }
    
    public void write(int val) throws IOException {
        raf.writeInt(val);
    }
    
    public void writeData(byte[] b, int off, int len) throws IOException {
        raf.write(b, off, len);
    }
    
    public void readData(byte[] b, int off, int len) throws IOException {
        raf.read(b, off, len);
    }
    
    public boolean hasMoreInt() throws IOException {
        int temp = 0;
        int sizeofInt = PrimitiveSizes.sizeof(temp);
        
        return raf.getFilePointer() + 2*sizeofInt <= raf.length();
    }
    
    public String getFileName() {
        return file.getName();
    }
    
    public void clear() throws IOException {
        raf.seek(0);
        byte[] bytes = new byte[(int) raf.length()];
        raf.write(bytes);
    }
    
    public void close() throws IOException {
        raf.close();
    }
    
}
